package com.hengxinguotong.zhihuichengjian.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.ui.app.MyApp;
import com.hengxinguotong.zhihuichengjian.bean.NVRVideoRes;
import com.hengxinguotong.zhihuichengjian.bean.Video;
import com.hengxinguotong.zhihuichengjian.bean.VideoRes;
import com.hengxinguotong.zhihuichengjian.nvr_video.PlaySurfaceView;
import com.hengxinguotong.zhihuichengjian.utils.DesUtils;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hikvision.netsdk.ExceptionCallBack;
import com.hikvision.netsdk.HCNetSDK;
import com.hikvision.netsdk.NET_DVR_DEVICEINFO_V30;
import com.hikvision.netsdk.PTZCommand;
import com.lidroid.xutils.http.RequestParams;
import android.view.SurfaceHolder.Callback;

import org.MediaPlayer.PlayM4.Player;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.jessyan.autosize.internal.CancelAdapt;

/**
 * Created by Administrator on 2017/8/24.
 */

public class NVRVideoActivity extends BaseActivity implements CancelAdapt,View.OnClickListener, Callback, SeekBar.OnSeekBarChangeListener{
    private int width;// 屏幕的宽度
    private int height;// 屏幕的高度

    private String strIP;
    private int nPort = 8000;
    private String strUser;
    private String strPsd;
    @BindView(R.id.surfaceView)
    SurfaceView m_osurfaceView;

    private NET_DVR_DEVICEINFO_V30 m_oNetDvrDeviceInfoV30 = null;


    private int m_iLogID = -1;                // return by NET_DVR_Login_v30
    private int m_iPlayID = -1;                // return by NET_DVR_RealPlay_V30


    private int m_iStartChan = 0;                // start channel no
    private int m_iChanNum = 0;                //通道个数
    private int m_iNum = 0;                //通道号
    private int m_ChnCount;
    private static PlaySurfaceView playView;

    private final String TAG = "VideoActivity";

//    @BindView(R.id.ll_beijing)
//    LinearLayout ll_beijing;
//    @BindView(R.id.iv_refresh)
//    ImageView iv_refresh;
    @BindView(R.id.rl_orientation)
    RelativeLayout rl_orientation;
    @BindView(R.id.rl_top)
    RelativeLayout rl_top;
    @BindView(R.id.rl_bottom)
    RelativeLayout rl_bottom;
    private boolean m_bNeedDecode = true;
    @BindView(R.id.iv_up)
    ImageView iv_up;
    @BindView(R.id.iv_left)
    ImageView iv_left;
    @BindView(R.id.iv_down)
    ImageView iv_down;
    @BindView(R.id.iv_right)
    ImageView iv_right;
    @BindView(R.id.iv_big)
    ImageView iv_big;
    @BindView(R.id.size_ll)
    LinearLayout sizeLl;
    @BindView(R.id.iv_next)
    ImageView iv_next;
    @BindView(R.id.iv_last)
    ImageView iv_last;
    @BindView(R.id.iv_small)
    ImageView iv_small;
    @BindView(R.id.iv_snap)
    ImageView iv_snap;
    @BindView(R.id.tv_project_name)
    TextView tvProjectName;
    @BindView(R.id.seekbar)
    SeekBar seekBar;
    private MyApp app;
    private String filePath;
    @BindView(R.id.tv_video_quality)
    TextView tv_video_quality;
    private int mStreamType = 1;
    private String quality = "标清";
    private int erroCount = 0;
    private boolean typeNext = true;
    private int dwSpeed = 3;//云台控制的速度，取值范围1-7；
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_video_nvr);
        ButterKnife.bind(this);
        app = (MyApp) getApplication();
        initMeasure();
        initView();
        initData();
//        getVideoList("加载中…");
    }

    private void initView(){
        seekBar.setOnSeekBarChangeListener(this);
//        iv_refresh.setVisibility(View.GONE);
//        ll_beijing.setVisibility(View.VISIBLE);
        playView = (PlaySurfaceView) findViewById(R.id.playSurfaceView);
        m_osurfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Date date = new Date(System.currentTimeMillis());
                startTime = (int) (date.getTime() / 1000);
                if (isOpen) {
                    startAnimation();
                } else {
                    isOpen = true;
//                    if(HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.TILT_UP, 0, dwSpeed)){
                    if (videoRes.getValue().getCameraList().get(index).getFlag() == 1) {
                        if(hasAction()){
                            rl_orientation.setVisibility(View.VISIBLE);
                        }
                    }else{
                        int erroId = HCNetSDK.getInstance().NET_DVR_GetLastError();
                        Log.i("NVR-piccfg错误信息erroId：", erroId + "");
                    }
                    rl_top.setVisibility(View.VISIBLE);
                    rl_bottom.setVisibility(View.VISIBLE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Date date = new Date(System.currentTimeMillis());
                            endTime = (int) (date.getTime() / 1000);
                            if (endTime - startTime > 5) {
                                startAnimation();
                            }

                        }
                    }, 6000);
                }
                return false;
            }
        });
    }

    private VideoRes videoRes;
    private int index;//摄像头的下标
    private void initData(){
        videoRes = (VideoRes) getIntent().getSerializableExtra("videoRes");
        index = getIntent().getIntExtra("position", 0);
        m_iNum = videoRes.getValue().getCameraList().get(index).getChannelNum() - 1;
        String nvrStr = videoRes.getValue().getNvrStr();
        try {
            nvrStr = DesUtils.decrypt(nvrStr, SPUtil.getString(this, "uuid"));
            String[] array = nvrStr.split("_");
            strIP = array[0];
            nPort = Integer.parseInt(array[1]);
            strUser = array[2];
            strPsd = array[3];
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!initeSdk()) {
            finish();
            return;
        }

        if (!initeActivity()) {
            finish();
            return;
        }
        startDownload();
        initLogin();
        startTiming();
//        ll_beijing.setVisibility(View.GONE);
    }

    private void getVideoList(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/video/getNvr/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    NVRVideoRes videoRes = gson.fromJson(json, NVRVideoRes.class);
                    strIP = videoRes.getValue().getIp();
                    strUser = videoRes.getValue().getUserName();
                    strPsd = videoRes.getValue().getPassword();
                    if (!initeSdk()) {
                        finish();
                        return;
                    }

                    if (!initeActivity()) {
                        finish();
                        return;
                    }
                    initLogin();
                    startTiming();
//                    ll_beijing.setVisibility(View.GONE);
                }else {
//                    iv_refresh.setVisibility(View.VISIBLE);
                    Toast.makeText(NVRVideoActivity.this, "登录失败,请稍后重试！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    /**
     * 获取屏幕的宽高
     */
    private void initMeasure() {
        width = getResources().getDisplayMetrics().widthPixels;
        height = getResources().getDisplayMetrics().heightPixels;
    }

    private PopupWindow pw;

    //弹出一个PopupWindow的窗体
    private void showPopupWindow(View view) {
        float w = (float) (width / 6.3);
        View v = LayoutInflater.from(this).inflate(R.layout.video_popup_window, null);
        TextView tv_high = (TextView) v.findViewById(R.id.tv_high);
        tv_high.setOnClickListener(this);
        TextView tv_sub = (TextView) v.findViewById(R.id.tv_sub);
        tv_sub.setOnClickListener(this);
        TextView tv_standard = (TextView) v.findViewById(R.id.tv_standard);
        tv_standard.setVisibility(View.GONE);
        pw = new PopupWindow(v, view.getWidth() - 10, (int) w);
        pw.setFocusable(true);
        pw.setBackgroundDrawable(new BitmapDrawable());
        pw.showAsDropDown(view, 0, 10);

    }

    @OnClick({R.id.iv_back, R.id.iv_refresh, R.id.iv_last, R.id.iv_snap, R.id.iv_next, R.id.tv_video_quality})
    public void onClick(View v) {
        Date date = new Date(System.currentTimeMillis());
        startTime = (int) (date.getTime() / 1000);
        switch (v.getId()) {
            case R.id.iv_back:
                stopMultiPreview();
                Cleanup();
                android.os.Process.killProcess(android.os.Process.myPid());
                break;
            case R.id.iv_refresh:
//                getVideoList("加载中…");
                initData();
                break;
            case R.id.iv_last:
                startDownload();
                erroCount = 0;
                if (m_iLogID >= 0 && m_iChanNum > 0) {
                    stopMultiPreview();
//                    if (m_iNum > 0) {
//                        m_iNum = m_iNum - 1;
//
//                    } else {
//                        m_iNum = m_ChnCount - 1;
//                    }
                    if (index > 0) {
                        index = index - 1;
                    } else {
                        index = videoRes.getValue().getCameraList().size() - 1;
                    }
                    m_iNum = videoRes.getValue().getCameraList().get(index).getChannelNum() - 1;
                    typeNext = false;
                    initPlay(mStreamType);
                }
                break;
            case R.id.iv_snap://拍照
                screenshot();
                break;
            case R.id.iv_next:
                startDownload();
                erroCount = 0;
                if (m_iLogID >= 0 && m_iChanNum > 0) {
                    stopMultiPreview();
//                    if (m_iNum < m_ChnCount - 1) {
//                        m_iNum = m_iNum + 1;
//
//                    } else {
//                        m_iNum = 0;
//                    }
                    if (index < (videoRes.getValue().getCameraList().size() - 1)) {
                        index = index + 1;
                    } else {
                        index = 0;
                    }
                    m_iNum = videoRes.getValue().getCameraList().get(index).getChannelNum() - 1;
                    typeNext = true;
                    initPlay(mStreamType);
                }
                break;
            case R.id.tv_video_quality:
                showPopupWindow(v);
                break;
            case R.id.tv_high:
                stopMultiPreview();
                erroCount = 0;
                startDownload();
                mStreamType = 0;
                pw.dismiss();
                quality = "高清";
                tv_video_quality.setText(quality);
                initPlay(0);
                break;
            case R.id.tv_sub:
                stopMultiPreview();
                erroCount = 0;
                startDownload();
                mStreamType = 1;
                pw.dismiss();
                quality = "标清";
                tv_video_quality.setText(quality);
                initPlay(1);
                break;
            default:
                break;
        }
        startTiming();
    }

    private void startTiming() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Date date = new Date(System.currentTimeMillis());
                endTime = (int) (date.getTime() / 1000);
                if (endTime - startTime > 5) {
                    startAnimation();
                }

            }
        }, 6000);
    }

    private void stopAnimation() {
        rl_orientation.clearAnimation();
        rl_top.clearAnimation();
        rl_bottom.clearAnimation();
    }

    private void startAnimation() {
        if (pw != null) {
            pw.dismiss();
        }
        rl_orientation.setVisibility(View.GONE);
        rl_top.setVisibility(View.GONE);
        rl_bottom.setVisibility(View.GONE);
        isOpen = false;
        stopDownLoad();
    }

    private int startTime;
    private int endTime;
    private boolean isOpen = true;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMultiPreview();
        Cleanup();
        android.os.Process.killProcess(android.os.Process.myPid());

    }

    private void onListeren() {
        if (m_iChanNum > 0) {

            iv_up.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    Date date = new Date(System.currentTimeMillis());
                    startTime = (int) (date.getTime() / 1000);
                    try {
                        if (m_iLogID < 0) {
                            Log.e(TAG, "please login on a device first");
                            return false;
                        }
                        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.TILT_UP, 0, dwSpeed)) {
                                Log.e(TAG, "start PAN_RIGHT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                                Toast.makeText(NVRVideoActivity.this, "设备不支持移动", Toast.LENGTH_SHORT).show();
                            } else {
                                Log.i(TAG, "start PAN_RIGHT succ");
                            }
                        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.TILT_UP, 1, dwSpeed)) {
                                Log.e(TAG, "stop PAN_RIGHT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                            } else {
                                Log.i(TAG, "stop PAN_RIGHT succ");
                            }
                        }

                        return true;
                    } catch (Exception err) {
                        Log.e(TAG, "error: " + err.toString());
                        return false;
                    }
                }
            });
            iv_left.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    Date date = new Date(System.currentTimeMillis());
                    startTime = (int) (date.getTime() / 1000);
                    try {
                        if (m_iLogID < 0) {
                            Log.e(TAG, "please login on a device first");
                            return false;
                        }
                        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {

                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.PAN_LEFT, 0, dwSpeed)) {
                                Log.e(TAG, "start PAN_LEFT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                                Toast.makeText(NVRVideoActivity.this, "设备不支持移动", Toast.LENGTH_SHORT).show();
                            } else {

                                Log.i(TAG, "start PAN_LEFT succ");
                            }
                        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.PAN_LEFT, 1, dwSpeed)) {
                                Log.e(TAG, "stop PAN_LEFT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                            } else {
                                Log.i(TAG, "stop PAN_LEFT succ");
                            }


                        }
                        return true;
                    } catch (Exception err) {
                        Log.e(TAG, "error: " + err.toString());
                        return false;
                    }
                }
            });
            iv_down.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    Date date = new Date(System.currentTimeMillis());
                    startTime = (int) (date.getTime() / 1000);
                    try {

                        if (m_iLogID < 0) {
                            Log.e(TAG, "please login on a device first");
                            return false;
                        }
                        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {

                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.TILT_DOWN, 0, dwSpeed)) {
                                Log.e(TAG, "start PAN_RIGHT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                                Toast.makeText(NVRVideoActivity.this, "设备不支持移动", Toast.LENGTH_SHORT).show();
                            } else {

                                Log.i(TAG, "start PAN_RIGHT succ");
                            }
                        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.TILT_DOWN, 1, dwSpeed)) {
                                Log.e(TAG, "stop PAN_RIGHT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                            } else {
                                Log.i(TAG, "stop PAN_RIGHT succ");
                            }

                        }

                        return true;
                    } catch (Exception err) {
                        Log.e(TAG, "error: " + err.toString());
                        return false;
                    }
                }
            });
            iv_right.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    Date date = new Date(System.currentTimeMillis());
                    startTime = (int) (date.getTime() / 1000);
                    try {
                        if (m_iLogID < 0) {
                            Log.e(TAG, "please login on a device first");
                            return false;
                        }

                        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.PAN_RIGHT, 0, dwSpeed)) {
                                Log.e(TAG, "start PAN_RIGHT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                                Toast.makeText(NVRVideoActivity.this, "设备不支持移动", Toast.LENGTH_SHORT).show();
                            } else {
                                Log.i(TAG, "start PAN_RIGHT succ");

                            }
                        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.PAN_RIGHT, 1, dwSpeed)) {
                                Log.e(TAG, "stop PAN_RIGHT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                            } else {
                                Log.i(TAG, "stop PAN_RIGHT succ");
                            }
                        }

                        return true;
                    } catch (Exception err) {
                        Log.e(TAG, "error: " + err.toString());
                        return false;
                    }
                }
            });
            iv_big.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    Date date = new Date(System.currentTimeMillis());
                    startTime = (int) (date.getTime() / 1000);
                    try {
                        if (m_iLogID < 0) {
                            Log.e(TAG, "please login on a device first");
                            return false;
                        }
                        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {

                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.ZOOM_IN, 0, dwSpeed)) {
                                Log.e(TAG, "start PAN_RIGHT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                                Toast.makeText(NVRVideoActivity.this, "设备不支持放大", Toast.LENGTH_SHORT).show();
                            } else {
                                Log.i(TAG, "start PAN_RIGHT succ");
                            }
                        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.ZOOM_IN, 1, dwSpeed)) {
                                Log.e(TAG, "stop PAN_RIGHT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                            } else {
                                Log.i(TAG, "stop PAN_RIGHT succ");
                            }
                        }

                        return true;
                    } catch (Exception err) {
                        return false;
                    }
                }
            });
            iv_small.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    Date date = new Date(System.currentTimeMillis());
                    startTime = (int) (date.getTime() / 1000);
                    try {
                        if (m_iLogID < 0) {
                            Log.e(TAG, "please login on a device first");
                            return false;
                        }
                        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {

                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.ZOOM_OUT, 0, dwSpeed)) {
                                Toast.makeText(NVRVideoActivity.this, "设备不支持缩小", Toast.LENGTH_SHORT).show();
                                Log.e(TAG, "start PAN_RIGHT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                            } else {
                                Log.i(TAG, "start PAN_RIGHT succ");
                            }
                        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

                            if (!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.ZOOM_OUT, 1, dwSpeed)) {
                                Log.e(TAG, "stop PAN_RIGHT failed with error code: " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                            } else {
                                Log.i(TAG, "stop PAN_RIGHT succ");
                            }
                        }

                        return true;
                    } catch (Exception err) {
                        Log.e(TAG, "error: " + err.toString());
                        return false;
                    }
                }
            });
        }

    }

    private void initLogin() {

        try {
            if (m_iLogID < 0) {
                // login on the device
                m_iLogID = loginDevice();
                m_ChnCount = m_iChanNum;
                if (m_iLogID < 0) {

                    stopDownLoad();
                    Toast.makeText(this, "登录失败,请稍后重试！", Toast.LENGTH_LONG).show();
                    Log.e("test", "This device logins failed!");
                    return;
                }
                // get instance of exception callback and set
                ExceptionCallBack oexceptionCbf = getExceptiongCbf();
                if (oexceptionCbf == null) {
                    return;
                }

                if (!HCNetSDK.getInstance().NET_DVR_SetExceptionCallBack(oexceptionCbf)) {
                    return;
                }
                Log.i("test", "Login sucess ****************************1***************************");
                initPlay(1);
                onListeren();
            } else {
                // whether we have logout
                if (!HCNetSDK.getInstance().NET_DVR_Logout_V30(m_iLogID)) {
                    return;
                }

                m_iLogID = -1;
            }
        } catch (Exception err) {
        }
    }

    private boolean initeSdk() {
        //init net sdk
        if (!HCNetSDK.getInstance().NET_DVR_Init()) {
            Log.e(TAG, "HCNetSDK init is failed!");
            return false;
        }
        HCNetSDK.getInstance().NET_DVR_SetLogToFile(3, "/mnt/sdcard/sdklog/", true);
        return true;
    }

    // GUI init
    private boolean initeActivity() {
//        findViews();
        m_osurfaceView.getHolder().addCallback(this);
        return true;
    }

    // get controller instance
    private void findViews() {
        m_osurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("m_iPlayID", m_iPlayID);
        super.onSaveInstanceState(outState);
        Log.i(TAG, "onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        m_iPlayID = savedInstanceState.getInt("m_iPlayID");
        super.onRestoreInstanceState(savedInstanceState);
        Log.i(TAG, "onRestoreInstanceState");
    }

    private void initPlay(int type) {

        try {
//            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
//                    hideSoftInputFromWindow(VideoActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            if (m_iLogID < 0) {
                return;
            }
            if (m_bNeedDecode) {
//                ll_beijing.setVisibility(View.VISIBLE);
                startMultiPreview(type);
            } else {

            }


        } catch (Exception err) {
        }

    }

    private int loginDevice() {
        // get instance
        m_oNetDvrDeviceInfoV30 = new NET_DVR_DEVICEINFO_V30();
        if (null == m_oNetDvrDeviceInfoV30) {
            Log.e(TAG, "HKNetDvrDeviceInfoV30 new is failed!");
            return -1;
        }
        // call NET_DVR_Login_v30 to login on, port 8000 as default_grey

        int iLogID = HCNetSDK.getInstance().NET_DVR_Login_V30(strIP, nPort, strUser, strPsd, m_oNetDvrDeviceInfoV30);
        if (iLogID < 0) {
            String failedString = "NET_DVR_Login is failed!Err:" + HCNetSDK.getInstance().NET_DVR_GetLastError();
            Log.e(TAG, failedString);
            return -1;
        }
        if (m_oNetDvrDeviceInfoV30.byChanNum > 0) {
            m_iStartChan = m_oNetDvrDeviceInfoV30.byStartChan;
            m_iChanNum = m_oNetDvrDeviceInfoV30.byChanNum;
        } else if (m_oNetDvrDeviceInfoV30.byIPChanNum > 0) {
            m_iStartChan = m_oNetDvrDeviceInfoV30.byStartDChan;
            m_iChanNum = m_oNetDvrDeviceInfoV30.byIPChanNum + m_oNetDvrDeviceInfoV30.byHighDChanNum * 256;
        }
        Log.i(TAG, "NET_DVR_Login is Successful!");

        return iLogID;
    }


    private ExceptionCallBack getExceptiongCbf() {
        ExceptionCallBack oExceptionCbf = new ExceptionCallBack() {
            public void fExceptionCallBack(int iType, int iUserID, int iHandle) {
                System.out.println("recv exception, type:" + iType);
            }
        };
        return oExceptionCbf;
    }


    public void Cleanup() {
        // release player resource
        Player.getInstance().freePort(m_iPlayID);
        m_iPlayID = -1;
        // release net SDK resource
        HCNetSDK.getInstance().NET_DVR_Cleanup();
        HCNetSDK.getInstance().NET_DVR_Logout_V30(m_iLogID);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                stopMultiPreview();
                Cleanup();
                android.os.Process.killProcess(android.os.Process.myPid());
                break;
            default:
                break;
        }

        return true;
    }

    private void startMultiPreview(int type) {
//        DisplayMetrics metric = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(metric);

//        if (playView == null) {
//            playView = new PlaySurfaceView(this);
//            playView.setParam(metric.widthPixels, width, height);
//            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
//                    width,
//                    height);
//
//            addContentView(playView, params);
//        }
        Log.i("test","m_iStartChan"+m_iStartChan +"m_iNum"+ m_iNum);
        playView.startPreview(m_iLogID, m_iStartChan + m_iNum, type);
        m_iPlayID = playView.m_iPreviewHandle;

        stopDownLoad();
        if (m_iPlayID < 0) {
            Log.i("test","NET_DVR_GetLastError ===》》》"+HCNetSDK.getInstance().NET_DVR_GetLastError());
            stopMultiPreview();
            if(erroCount >= 2){
                erroCount = 0;
                if(typeNext){
                    if (index < (videoRes.getValue().getCameraList().size() - 1)) {
                        index = index + 1;
                    } else {
                        index = 0;
                    }
                }else{
                    if (index > 0) {
                        index = index - 1;
                    } else {
                        index = videoRes.getValue().getCameraList().size() - 1;
                    }
                }
                m_iNum = videoRes.getValue().getCameraList().get(index).getChannelNum() - 1;
            }else{
                if(type == 0){
                    type = 1;
                    quality = "标清";
                }else{
                    type = 0;
                    quality = "高清";
                }
            }
            erroCount ++;
            initPlay(type);
//            Toast.makeText(this,m_iNum + 1+" 通道视频播放失败", Toast.LENGTH_SHORT).show();
        }else {
//            Toast.makeText(this,m_iNum + 1+" 通道视频播放成功",Toast.LENGTH_SHORT).show();
//            ll_beijing.setVisibility(View.GONE);

            tv_video_quality.setText(quality);
            Video video = videoRes.getValue().getCameraList().get(index);
            tvProjectName.setText(video.getName());
            erroCount = 0;
//            if(!HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.TILT_UP, 0, dwSpeed)){
            if(video.getFlag() == 0){//标识.1:可云台控制;0:不能云台控制
                rl_orientation.setVisibility(View.GONE);
//                        sizeLl.setVisibility(View.GONE);
//                seekBar.setVisibility(View.GONE);
//                int erroId = HCNetSDK.getInstance().NET_DVR_GetLastError();
//                Log.i("NVR-piccfg错误信息erroId：", erroId + "");
            }else{
                if(hasAction()){
                    rl_orientation.setVisibility(View.VISIBLE);
//                    sizeLl.setVisibility(View.VISIBLE);
//                    seekBar.setVisibility(View.VISIBLE);
                }else{
                    rl_orientation.setVisibility(View.GONE);
//                            sizeLl.setVisibility(View.GONE);
//                    seekBar.setVisibility(View.GONE);
                }
//                HCNetSDK.getInstance().NET_DVR_PTZControlWithSpeed_Other(m_iLogID, m_iStartChan + m_iNum, PTZCommand.TILT_UP, 1, dwSpeed);
            }
        }
    }

    private void stopMultiPreview() {

        if (playView != null) {

            playView.stopPreview();
        }
        m_iPlayID = -1;
    }

    Dialog progressDialog;

    public void startDownload() {
        String marked = "视频加载中…";
        Context context = this;
        if (progressDialog == null) {
            progressDialog = Utils.createLoadingDialog(context, marked);
            progressDialog.show();
        } else {
            if (!progressDialog.isShowing()) {
                stopDownLoad();
                startDownload();
            }
        }
    }


    public void stopDownLoad() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        m_osurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        if (-1 == m_iPlayID) {
            return;
        }
        Surface surface = holder.getSurface();
        if (true == surface.isValid()) {
            if (false == Player.getInstance().setVideoWindow(m_iPlayID, 0, holder)) {
                Log.e(TAG, "Player setVideoWindow failed!");
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (-1 == m_iPlayID) {
            return;
        }
        if (true == holder.getSurface().isValid()) {
            if (false == Player.getInstance().setVideoWindow(m_iPlayID, 0, null)) {
                Log.e(TAG, "Player setVideoWindow failed!");
            }
        }
    }

    private void screenshot() {
        try {
//            if(m_iPlayID <=0)
//            {
//                Log.e(TAG, "please start preview first");
//                return;
//            }
            Player.MPInteger stWidth = new Player.MPInteger();
            Player.MPInteger stHeight = new Player.MPInteger();
            if (!Player.getInstance().getPictureSize(0, stWidth, stHeight)) {
                Log.e(TAG, "getPictureSize failed with error code:" + Player.getInstance().getLastError(0));
                return;
            }
            int nSize = 5 * stWidth.value * stHeight.value;
            byte[] picBuf = new byte[nSize];
            Player.MPInteger stSize = new Player.MPInteger();
            if (!Player.getInstance().getJPEG(0, picBuf, nSize, stSize)) {
                Log.e(TAG, "getJPEG failed with error code:" + Player.getInstance().getLastError(0));
                return;
            }

            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss");
            String date = sDateFormat.format(new java.util.Date());
            FileOutputStream file = new FileOutputStream("/mnt/sdcard/" + date + ".jpg");
            file.write(picBuf, 0, stSize.value);
            file.close();

            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(new File("/mnt/sdcard/" + date + ".jpg"));
            intent.setData(uri);
            sendBroadcast(intent);//这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！，记得要传你更新的file哦
            Toast.makeText(NVRVideoActivity.this, "图片捕获成功，请在相册中查看！", Toast.LENGTH_SHORT).show();
        } catch (Exception err) {
            Log.e(TAG, "error: " + err.toString());
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        //数值改变
        dwSpeed = progress + 1;
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        //开始拖动
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        //停止拖动
    }
}
